<template>
    <div>
        <BasicDialogVue :data="dialog" @close="onCloseDialog(formRef)">
            <template #content>
                <el-form ref="formRef" :model="formData" label-width="120px" :rules="rules">
                    <el-form-item label="手机号码：" prop="phone">
                        <el-input type="number" v-model="formData.phone" clearable placeholder="请输入手机号码" />
                    </el-form-item>
                    <el-form-item label="客户名称：" prop="customerName">
                        <el-input v-model="formData.customerName" clearable placeholder="请输入客户名称" />
                    </el-form-item>
                    <el-form-item label="区域：" prop="areaName">
                        <div style="width: 100%; display: flex">
                            <el-select style="width: 32%; margin-right: 2%" v-model="privince.id" @change="getCityData">
                                <el-option
                                    v-for="itemOption in privinceOptions"
                                    :key="itemOption.id"
                                    :label="itemOption.label"
                                    :value="itemOption.id"
                                />
                            </el-select>
                            <el-select style="width: 32%; margin-right: 2%" v-model="city.id" @change="getAreaData">
                                <el-option
                                    v-for="itemOption in cityOptions"
                                    :key="itemOption.id"
                                    :label="itemOption.label"
                                    :value="itemOption.id"
                                />
                            </el-select>
                            <el-select
                                style="width: 32%"
                                v-model="area.id"
                                v-if="hasArea"
                                @change="
                                    (res: any) => {
                                        console.log(res, privince)
                                        areaOptions.forEach(item => {
                                            if (item.id === res) {
                                                area.label = item.label
                                            }
                                        })
                                        //如果是直辖市，则不显示城市，显示直辖市的名称
                                        if (
                                            [820000, 810000, 110000, 120000, 310000, 500000].includes(
                                                Number(privince.id)
                                            )
                                        ) {
                                            //$emit('change', [privince, privince])
                                        }
                                    }
                                "
                            >
                                <el-option
                                    v-for="itemOption in areaOptions"
                                    :key="itemOption.id"
                                    :label="itemOption.label"
                                    :value="itemOption.id"
                                />
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="查看班别：" prop="viewedClassName">
                        <el-input v-model="formData.viewedClassName" clearable placeholder="请输入查看班别" />
                    </el-form-item>
                    <el-form-item label="报名门店：" prop="storeName">
                        <el-input v-model="formData.storeName" clearable placeholder="请输入报名门店" />
                    </el-form-item>
                    <el-form-item label="数据来源：" prop="dataSource">
                        <el-select
                            clearable
                            placeholder="请选择数据来源"
                            v-model="formData.dataSource"
                            multiple
                            style="width: 100%"
                        >
                            <el-option
                                v-for="itemOption in DICT_DATA.get('dataSource')"
                                :key="itemOption.value"
                                :label="itemOption.label"
                                :value="itemOption.value"
                            />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="系统来源：" prop="systemSource">
                        <el-select
                            clearable
                            placeholder="请选择系统来源"
                            v-model="formData.systemSource"
                            style="width: 100%"
                        >
                            <el-option
                                v-for="itemOption in DICT_DATA.get('systemSource')"
                                :key="itemOption.value"
                                :label="itemOption.label"
                                :value="itemOption.value"
                            />
                        </el-select>
                    </el-form-item> -->

                    <el-form-item label="分销人员姓名：" prop="referrerName">
                        <el-input v-model="formData.referrerName" clearable placeholder="请输入分销人员姓名" />
                    </el-form-item>
                    <el-form-item label="分销人员手机：">
                        <el-input v-model="formData.referrerPhone" clearable placeholder="请输入分销人员手机" />
                    </el-form-item>
                </el-form>
                <div class="btn">
                    <el-button @click="onCloseDialog(formRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
                </div>
            </template>
        </BasicDialogVue>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance } from 'element-plus'
import { ref, reactive, watchEffect, onMounted } from 'vue'
import BasicDialogVue from '@/components/baseDialog/Index.vue'
import { districtChildren } from '@/apis/system'
import { DICT_DATA } from '@/utils/dict-data'
import { ru } from 'element-plus/es/locale'
import { generateRandomLetters, regMobile } from '@/utils'
import { addClue, clueOperateInterface } from '@/apis/clue'

const props = defineProps(['data'])
const emits = defineEmits(['close'])
const formRef = ref()
const dialog = reactive({
    visible: false,
    title: '创建线索',
    width: '600px',
    type: 'create'
})

const formData = reactive({
    areaName: '',
    cityName: '',
    createTime: '',
    customerId: '',
    customerName: '',
    dataSource: [],
    phone: '',
    referrerName: '',
    referrerPhone: '',
    schoolId: '',
    schoolName: '',
    storeName: '',
    systemSource: '2',
    viewedClassName: ''
})
// 手机号码验证
const validatePhonePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入手机号'))
    } else {
        if (regMobile(value)) {
            callback()
        } else {
            callback(new Error('手机号不正确'))
        }
    }
}

const rules = {
    customerName: [{ required: false, message: '请输入客户名称', trigger: 'blur' }],
    phone: [{ required: true, validator: validatePhonePass, trigger: 'blur' }],
    dataSource: [{ required: true, message: '请选择数据来源', trigger: 'blur' }],
    systemSource: [{ required: true, message: '请选择系统来源', trigger: 'change' }]
    // referrerPhone: [{ required: false, validator: validatePhonePass, trigger: 'blur' }]
}

const privince = reactive<{ label: string; id: string }>({ label: '广东', id: '440000' })
const privinceOptions = reactive<{ label: string; id: string }[]>([])

const city = reactive<{ label: string; id: string }>({ label: '深圳市', id: '440300' })
const cityOptions = reactive<{ label: string; id: string }[]>([])

const area = reactive<{ label: string; id: string }>({ label: '', id: '' })
const areaOptions = reactive<{ label: string; id: string }[]>([])

const hasArea = ref(true)

//判断是否是直辖市
const isMunicipality = (id: string) => {
    return [820000, 810000, 110000, 120000, 310000, 500000].includes(Number(id))
}

watchEffect(() => {
    dialog.visible = props.data.visible
})

onMounted(() => {
    setInitData()
})

//设置初始值
const setInitData = () => {
    districtChildren().then((res: any) => {
        if (Number(res.data.code) === 200) {
            privinceOptions.length = 0
            cityOptions.length = 0
            res.data.result.forEach((item: any) => {
                privinceOptions.push({
                    label: item.fullname,
                    id: item.id
                })
            })
        }
    })
    districtChildren(privince.id).then((res: any) => {
        if (Number(res.data.code) === 200) {
            cityOptions.length = 0
            res.data.result.forEach((item: any) => {
                cityOptions.push({
                    label: item.fullname,
                    id: item.id
                })
            })
        }
    })
    districtChildren(city.id).then((res: any) => {
        if (Number(res.data.code) === 200) {
            areaOptions.length = 0
            res.data.result.forEach((item: any) => {
                areaOptions.push({
                    label: item.fullname,
                    id: item.id
                })
            })
        }
    })
}

const getCityData = (res: any) => {
    console.log('privince', res)
    privinceOptions.forEach(item => {
        if (item.id === res) {
            privince.label = item.label
        }
    })

    if (isMunicipality(res)) {
        hasArea.value = false
    } else {
        hasArea.value = true
    }
    districtChildren(res).then((res: any) => {
        if (Number(res.data.code) === 200) {
            cityOptions.length = 0
            city.label = ''
            city.id = ''
            res.data.result.forEach((item: any) => {
                cityOptions.push({
                    label: item.fullname,
                    id: item.id
                })
            })
        }
    })
}

const getAreaData = (res: any) => {
    console.log('city', res)
    cityOptions.forEach(item => {
        if (item.id === res) {
            city.label = item.label
        }
    })
    districtChildren(res).then((res: any) => {
        if (Number(res.data.code) === 200) {
            areaOptions.length = 0
            area.label = ''
            area.id = ''
            res.data.result.forEach((item: any) => {
                areaOptions.push({
                    label: item.fullname,
                    id: item.id
                })
            })
        }
    })
}

//清空表格数据
const onReset = () => {
    formData.areaName = ''
    formData.cityName = ''
    formData.createTime = ''
    formData.customerId = ''
    formData.customerName = ''
    formData.dataSource = []
    formData.phone = ''
    formData.referrerName = ''
    formData.referrerPhone = ''
    formData.schoolId = ''
    formData.schoolName = ''
    formData.storeName = ''
    formData.systemSource = '2'
    formData.viewedClassName = ''
    privince.id = '440000'
    privince.label = '广东省'
    city.id = '440300'
    city.label = '深圳市'
    area.id = ''
    area.label = ''
    hasArea.value = true
}

//监听弹窗关闭
const onCloseDialog = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialog.visible = false
    onReset()
    emits('close')
}

//监听弹窗点击确定按钮
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!', formData, privince, city, area)
            const dataSource = formData.dataSource as string[]
            const data: clueOperateInterface = {
                areaName: privince.label,
                cityName: city.label,
                createTime: '',
                customerId: new Date().getTime() + generateRandomLetters(),
                customerName: formData.customerName,
                dataSource: formData.dataSource.join(','),
                phone: formData.phone,
                referrerName: formData.referrerName,
                referrerPhone: formData.referrerPhone,
                schoolId: '20240424155811pktmdpazqpl92sb17kfezv',
                schoolName: '深港驾校',
                storeName: formData.storeName,
                systemSource: Number(formData.systemSource),
                viewedClassName: formData.viewedClassName
            }

            if (isMunicipality(privince.id)) {
                data.cityName = privince.label
                data.areaName = city.label
            } else {
                data.cityName = city.label
                data.areaName = area.label
            }

            console.log('data!', data)
            addClue(data).then(res => {
                if (Number(res.data.code) === 200) {
                    formEl.resetFields()
                    onReset()
                    ElMessage.success('新增成功')
                    emits('close')
                }
            })
        }
    })
}
</script>

<style scoped lang="scss">
.btn {
    display: flex;
    justify-content: center;
}
</style>
